package jnpf.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jnpf.base.service.SuperServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.config.ConfigValueUtil;
import jnpf.entity.DocumentEntity;
import jnpf.entity.DocumentShareEntity;
import jnpf.entity.DocumentVersionEntity;
import jnpf.entity.OrderEntity;
import jnpf.mapper.DocumentMapper;
import jnpf.model.document.PageDocument;
import jnpf.service.DocumentService;
import jnpf.service.DocumentShareService;
import jnpf.service.DocumentVersionService;
import jnpf.util.FileUtil;
import jnpf.util.RandomUtil;
import jnpf.util.StringUtil;
import jnpf.util.UserProvider;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 知识文档
 *
 * @author JNPF开发平台组
 * @copyright 引迈信息技术有限公司
 * @date 2019年9月26日 上午9:18
 */
@Service
public class DocumentServiceImpl extends SuperServiceImpl<DocumentMapper, DocumentEntity> implements DocumentService {

    @Autowired
    private UserProvider userProvider;
    @Autowired
    private DocumentShareService documentShareService;
    @Autowired
    private ConfigValueUtil configValueUtil;
    @Autowired
    private DocumentVersionService documentVersionService;



    @Override
    public List<DocumentEntity> getDocList(PageDocument ent){
        ent.setCreatorUserId(userProvider.get().getUserId());
        return this.baseMapper.getDocList(ent);
    }
    @Override
    public List<DocumentEntity> getDocListByFileExtension(List<String> types){
        return this.baseMapper.getDocListByFileExtension(types);
    }
    @Override
    public Integer getListTotalByFileExtension(List<String> types){
        return this.baseMapper.getListTotalByFileExtension(types);
    }

    @Override
    public Integer getListTotal(PageDocument ent){
        ent.setCreatorUserId(userProvider.get().getUserId());
        return this.baseMapper.getListTotal(ent);
    }




    @Override
    public List<DocumentEntity> getFolderList() {
        QueryWrapper<DocumentEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(DocumentEntity::getCreatorUserId, userProvider.get().getUserId())
                .eq(DocumentEntity::getType, 0)
                .eq(DocumentEntity::getEnabledMark, 1)
                .orderByAsc(DocumentEntity::getCreatorTime);
        return this.list(queryWrapper);
    }

    @Override
    public List<DocumentEntity> getAllList(String parentId) {
        QueryWrapper<DocumentEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(DocumentEntity::getCreatorUserId, userProvider.get().getUserId())
                .eq(DocumentEntity::getEnabledMark, 1)
                .eq(DocumentEntity::getParentId, parentId)
                .orderByDesc(DocumentEntity::getCreatorTime);
        return this.list(queryWrapper);
    }



    @Override
    public List<DocumentEntity> getTrashList() {
        QueryWrapper<DocumentEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(DocumentEntity::getCreatorUserId, userProvider.get().getUserId())
                .eq(DocumentEntity::getEnabledMark, 0)
                .orderByDesc(DocumentEntity::getDeleteTime);
        return this.list(queryWrapper);
    }

    @Override
    public List<DocumentEntity> getShareOutList(PageDocument ent) {
        return this.baseMapper.getShareOutList(ent);
    }

    @Override
    public Integer getShareOutListCount(PageDocument ent) {
        return this.baseMapper.getShareOutListCount(ent);
    }



    @Override
    public List<DocumentEntity> getShareTomeList() {
        return this.baseMapper.getShareTomeList(userProvider.get().getUserId());
    }

    @Override
    public List<DocumentShareEntity> getShareUserList(List<String> docList) {
        QueryWrapper<DocumentShareEntity> queryWrapper = new QueryWrapper<>();
        if(docList.size()>0){
            queryWrapper.lambda().in(DocumentShareEntity::getDocumentId, docList);
        }
        return documentShareService.list(queryWrapper);
    }

    @Override
    public DocumentEntity getInfo(String id) {
        QueryWrapper<DocumentEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(DocumentEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    public void delete(DocumentEntity entity) {
        entity.setDeleteTime(new Date());
        entity.setDeleteUserId(userProvider.get().getUserId());
        entity.setEnabledMark(0);
        this.updateById(entity);
    }

    @Override
    public void create(DocumentEntity entity) {
        entity.setId(RandomUtil.uuId());
        entity.setCreatorUserId(userProvider.get().getUserId());
        entity.setEnabledMark(1);
        this.save(entity);
    }

    @Override
    public boolean update(String id, DocumentEntity entity) {
        entity.setId(id);
        entity.setLastModifyTime(new Date());
        entity.setLastModifyUserId(userProvider.get().getUserId());
        return this.updateById(entity);
    }

    @Override
    @DSTransactional
    public void shareCreate(String[] documentIds, String[] shareUserId) {
        List<DocumentShareEntity> entitys = new ArrayList<>();
        for(String documentId : documentIds) {
            if (shareUserId.length == 0) {
                DocumentShareEntity entity = new DocumentShareEntity();
                entity.setId(RandomUtil.uuId());
                entity.setDocumentId(documentId);
                entity.setShareUserId(null);
                entity.setShareTime(new Date());
                entity.setCreateUser(userProvider.get().getUserId());
                entitys.add(entity);
            } else {
                for (String item : shareUserId) {
                    DocumentShareEntity entity = new DocumentShareEntity();
                    entity.setId(RandomUtil.uuId());
                    entity.setDocumentId(documentId);
                    entity.setShareUserId(item);
                    entity.setShareTime(new Date());
                    entity.setCreateUser(userProvider.get().getUserId());
                    entitys.add(entity);
                }
            }
        }
        QueryWrapper<DocumentEntity> queryWrapper = new QueryWrapper<>();
        for(String documentId : documentIds) {
            DocumentEntity entity = this.getOne(queryWrapper.lambda().eq(DocumentEntity::getId, documentId));
            if (entity != null) {
                entity.setIsShare(1);
                entity.setShareTime(new Date());
                this.updateById(entity);
                QueryWrapper<DocumentShareEntity> wrapper = new QueryWrapper<>();
                wrapper.lambda().eq(DocumentShareEntity::getDocumentId, documentId);
                documentShareService.remove(wrapper);
            }
        }
        for (DocumentShareEntity shareEntity : entitys) {
            documentShareService.save(shareEntity);
        }
    }

    @Override
    @DSTransactional
    public void shareCancel(String[] documentIds) {
        for(String documentId :documentIds) {
            QueryWrapper<DocumentEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(DocumentEntity::getId, documentId);
            DocumentEntity entity = this.getOne(queryWrapper);
            if (entity != null) {
                entity.setIsShare(0);
                entity.setShareTime(new Date());
                this.updateById(entity);
                QueryWrapper<DocumentShareEntity> wrapper = new QueryWrapper<>();
                wrapper.lambda().eq(DocumentShareEntity::getDocumentId, documentId);
                documentShareService.remove(wrapper);
            }
        }
    }

    @Override
    @DSTransactional
    public void trashDelete(String[] folderIds) {
        for(String folderId : folderIds ){
            DocumentEntity entity = this.getInfo(folderId);
            if(entity!=null){
                this.removeById(folderId);
                FileUtil.deleteFile(configValueUtil.getDocumentFilePath() + entity.getFilePath());
            }
            //删除所有版本数据及文件
            QueryWrapper<DocumentVersionEntity> verquery = new QueryWrapper<>();
            verquery.lambda().eq(DocumentVersionEntity::getDocid,folderId);
            List<DocumentVersionEntity> verlist = this.documentVersionService.list(verquery);
            for(DocumentVersionEntity versionEntity : verlist){
                FileUtil.deleteFile(versionEntity.getMainurl());
                documentVersionService.delete(versionEntity);
            }
        }

//        List<DocumentEntity> list = this.baseMapper.GetChildList(folderId);
//        List<String> deleteId = new ArrayList<>();
//        for (DocumentEntity entity : list) {
//            if(!StringUtil.isEmpty(entity.getFilePath())){
//                FileUtil.deleteFile(configValueUtil.getDocumentFilePath() + entity.getFilePath());
//            }
//            deleteId.add(entity.getId());
//        }
//        this.removeByIds(deleteId);
    }

    @Override
    public boolean trashRecovery(String id) {
       return retBool(this.baseMapper.trashRecovery(id));
    }

    @Override
    public boolean moveTo(String id, String toId) {
        DocumentEntity entity = this.getInfo(id);
        if(entity!=null){
            entity.setParentId(toId);
            this.updateById(entity);
           return true;
        }
       return false;
    }

    @Override
    public boolean isExistByFullName(String fullName, String id, String parentId) {
        String userId=userProvider.get().getUserId();
        QueryWrapper<DocumentEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(DocumentEntity::getFullName,fullName).eq(DocumentEntity::getEnabledMark, 1).eq(DocumentEntity::getCreatorUserId,userId);
        queryWrapper.lambda().eq(DocumentEntity::getParentId, parentId);
        if(!StringUtil.isEmpty(id)){
            queryWrapper.lambda().ne(DocumentEntity::getId, id);
        }
        return this.count(queryWrapper) > 0 ? true : false;
    }
}
